package cn.liu.http.utils;


import com.alibaba.fastjson2.JSONObject;
import org.apache.http.Header;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.pool.PoolStats;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author LIU
 * @version 1.0
 * @date 2024/9/9 14:51
 * @description TODO
 */
public class HttpUtils {
    private static CloseableHttpClient closeableHttpClient;
    private static PoolingHttpClientConnectionManager cm;

    /**
     *  http连接池配置
     */
    static {
        final HttpClientBuilder builder = HttpClients.custom();

        // 连接池配置
        cm = new PoolingHttpClientConnectionManager();
        // 连接池最大连接数
        cm.setMaxTotal(50);
        // ip/域名+端口：就是一个路由，每个路由分配多少连接
        cm.setDefaultMaxPerRoute(50);
        builder.setConnectionManager(cm);

        // 默认请求配置
        final RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(10000)
                .setSocketTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .build();
        builder.setDefaultRequestConfig(requestConfig);

        // 添加默认请求头
        final ArrayList<Header> list = new ArrayList<>();
        list.add(new BasicHeader("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"));
        builder.setDefaultHeaders(list);

        closeableHttpClient = builder.build();
    }



    public static String sendGet(String url, Map<String,String> params){
        HttpGet httpGet = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            httpGet = new HttpGet(url);
            // 设置参数
            if (null != params && params.size() > 0){
                List<BasicNameValuePair> pairList = new ArrayList<>();
                params.forEach((x,y) -> pairList.add(new BasicNameValuePair(x,y)));
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairList,"utf-8");
                // 将参数转成page=1&limit=5格式
                String param = EntityUtils.toString(urlEncodedFormEntity, "utf-8");
                httpGet = new HttpGet(url+"?"+param);
            }
            response = closeableHttpClient.execute(httpGet);
            result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            printStat();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            close(response,httpGet,null);
        }
        return result;
    }

    public static String sendPost(String url, Map<String,String> params){
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            httpPost = new HttpPost(url);
            // 设置参数
            if (null != params && params.size() > 0){
                List<BasicNameValuePair> pairList = new ArrayList<>();
                params.forEach((x,y) -> pairList.add(new BasicNameValuePair(x,y)));
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairList,"utf-8");
                httpPost.setEntity(urlEncodedFormEntity);
            }
            response = closeableHttpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            close(response,httpPost,null);
        }
        return result;
    }


    public static String sendPostJson(String url, Map<String,String> params){
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            httpPost = new HttpPost(url);
            // 设置参数
            if (null != params && params.size() > 0){
                String paramJson = JSONObject.toJSONString(params);
                StringEntity stringEntity = new StringEntity(paramJson,"utf-8");
                stringEntity.setContentType("application/json;charset=utf-8");
                httpPost.setEntity(stringEntity);
            }
            response = closeableHttpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            close(response,httpPost,null);
        }
        return result;
    }


    public static void printStat(){
        final PoolStats totalStats = cm.getTotalStats();
        System.out.printf("活跃连接数：%d，已占用连接数：%d，Pending：%d", totalStats.getAvailable() , totalStats.getLeased() ,totalStats.getPending());
        System.out.println();
    }

    public static void close(CloseableHttpResponse response, HttpRequestBase httpRequestBase, CloseableHttpClient httpClient){
        if (httpRequestBase!= null){
            httpRequestBase.releaseConnection();
        }

        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }



        try {
            if (httpClient != null){
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
